package top.hundreds.oasys.controller.FrontController;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.hundreds.common.crud.bean.PageParam;
import top.hundreds.common.web.api.ApiResult;
import top.hundreds.oasys.bean.entity.Papers;
import top.hundreds.oasys.service.PapersService;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

/**
 * (Papers)表控制层
 *
 * @author lcf
 * @since 2021-01-29 19:18:37
 */
@RestController
@RequestMapping("/front/papers")
public class PapersController {
    /**
     * 服务对象
     */
    @Resource
    private PapersService papersService;

    @Value("${upload.img.path}")
    private String imagePath;

    @Value("${upload.img.url}")
    private String imagUrl;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Papers selectOne(Long id) {
        return this.papersService.get(id);
    }

    @PostMapping("upload")
    public ApiResult<String> upload(@RequestBody MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extName = FileUtil.extName(fileName);
        String fileType = this.papersService.getFileType(extName);
        String uuid = IdUtil.simpleUUID();
        String imagePathName = imagePath + uuid + "-" + file.getOriginalFilename();
        String imageAddress = imagUrl + uuid + "-" + file.getOriginalFilename();
        try {
            file.transferTo(new File(imagePathName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ApiResult.success(imageAddress);
    }

    @PostMapping("list")
    public ApiResult<List<Papers>> list(@RequestBody PageParam<Papers> pageParam) {

        Page<Papers> page = this.papersService.getPage(pageParam);
        List<Papers> list = page.getRecords();
        // 判断权限
        return ApiResult.success(list);
    }

    @DeleteMapping("remove")
    public ApiResult<String> remove(Long id) {
        this.papersService.delete(id);
        return ApiResult.success();
    }
}
